package com.sebiotec.manager.ui.fragment.message;

import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.allen.library.RxHttpUtils;
import com.sebiotec.basecommon.utils.base.BaseLazyLoadingFragment;
import com.sebiotec.basecommon.utils.entity.event.CountEvent;
import com.sebiotec.basecommon.utils.entity.event.MsgRefreshEvent;
import com.sebiotec.basecommon.utils.tools.SoftKeyBoardListener;

import com.sebiotec.manager.R;
import com.sebiotec.manager.R2;
import com.sebiotec.manager.adapt.MessageListAdapt;
import com.sebiotec.manager.model.MessageEntity;
import com.sebiotec.manager.model.response.MessListResponse;
import com.sebiotec.manager.viewmodel.MessageViewModel;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.statelayout.MultipleStatusView;
import com.xw.repo.XEditText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MessageFragment extends BaseLazyLoadingFragment {
    @BindView(R2.id.ed_history_seach)
    XEditText edHistorySeach;
    @BindView(R2.id.iv_search)
    ImageView ivSearch;
    @BindView(R2.id.rl_shape)
    RelativeLayout rlShape;
    @BindView(R2.id.recy_message)
    RecyclerView recyMessage;
    @BindView(R2.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R2.id.multiple_status_view)
    MultipleStatusView multipleStatusView;
    private boolean isShow = true;
    private MessageViewModel mMessageViewModel;

    private List<MessageEntity> messageEntities = new ArrayList<>();
    private MessageListAdapt adapt;
    private String mSeach;
    private MiniLoadingDialog dialog;
    private  int PageSize=30;
    private  int PageIndex=1;
    @Override
    protected String getLogTag() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.man_fragment_message;
    }

    @Override
    protected void initView(View root) {
        mMessageViewModel = ViewModelProviders.of(this).get(MessageViewModel.class);
        EventBus.getDefault().register(this);
        initUi();
    }
    @Override
    protected void onFragmentResume() {
        super.onFragmentResume();
        if (dialog!=null){
            dialog.show();
        }else{
            dialog=new MiniLoadingDialog(getActivity(),getString(R.string.tip_loading_message));
            dialog.show();
        }
        EventBus.getDefault().post(new CountEvent());
        initData();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dialog!=null){
            dialog.dismiss();
            dialog=null;
        }
        EventBus.getDefault().unregister(this);
        RxHttpUtils.cancel("ManagerMessage");
    }

    private void initUi() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyMessage.setLayoutManager(linearLayoutManager);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {

                mSeach = "";
                edHistorySeach.setTextEx("");
                refreshlayout.setEnableLoadMore(true);
                PageIndex = 1;

                mMessageViewModel.getData(mSeach, PageSize, PageIndex, new MessageViewModel.MyHistoryDataCallBack<Object>() {
                    @Override
                    public void onDataSuccessCallBack(Object o) {
                        MessListResponse bean = (MessListResponse) o;
                        if (bean.getRows() == null || bean.getRows().size() == 0) {
                            multipleStatusView.showEmpty();
                            refreshlayout.finishRefresh();//传入false表示刷新失败
                        } else {
                            PageIndex++;
                            if (adapt != null) {
                                adapt.setNewData(bean.getRows());
                                recyMessage.setAdapter(adapt);
                            } else {
                                adapt = new MessageListAdapt(getActivity());
                                adapt.addData(bean.getRows());
                                recyMessage.setAdapter(adapt);
                            }


                            refreshlayout.finishRefresh();

                        }

                    }

                    @Override
                    public void onDataFailCallBack(Object o) {
                        refreshlayout.finishRefresh(false);
                    }
                });

            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(final RefreshLayout refreshlayout) {

                mMessageViewModel.getData(mSeach, PageSize, PageIndex, new MessageViewModel.MyHistoryDataCallBack<Object>() {
                    @Override
                    public void onDataSuccessCallBack(Object o) {

                        MessListResponse bean = (MessListResponse) o;

                        if (bean.getRows() == null || bean.getRows().size() == 0) {
                            refreshlayout.setNoMoreData(true);
                        } else {
                            PageIndex++;
                            refreshlayout.finishLoadMore();
                            adapt.addData(bean.getRows());

                        }

                    }

                    @Override
                    public void onDataFailCallBack(Object o) {
                        refreshlayout.finishLoadMore(false/*,false*/);//传入false表示加载失败
                    }
                });






            }
        });
        edHistorySeach.setOnXFocusChangeListener(new XEditText.OnXFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    rlShape.setBackground(getActivity().getDrawable(R.drawable.ll_half_shape_ed));
                    ivSearch.setImageResource(R.drawable.seach_white);
                } else {
                    // 此处为失去焦点时的处理内容
                    rlShape.setBackground(getActivity().getDrawable(R.drawable.ll_half_shape));
                    ivSearch.setImageResource(R.drawable.search);
                }
            }
        });
        edHistorySeach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edHistorySeach.setFocusable(true);
                edHistorySeach.setFocusableInTouchMode(true);
                edHistorySeach.requestFocus();
            }
        });
        SoftKeyBoardListener.setListener(getActivity(), new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {

            }

            @Override
            public void keyBoardHide(int height) {
                edHistorySeach.setFocusable(false);
            }
        });

        // XToast.error(getContext(),"点击了").show();
        //                 startActivity(MessageDetailActivity.class);


    }

    ;

    @OnClick({R2.id.ed_history_seach, R2.id.iv_search})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.ed_history_seach) {
        } else if (id == R.id.iv_search) {
            mSeach = edHistorySeach.getTextEx().toString().trim();
            initData();
        }
    }


    public void initData() {
        PageIndex = 1;
        refreshLayout.setNoMoreData(false);
        mMessageViewModel.getData(mSeach, PageSize, PageIndex, new MessageViewModel.MyHistoryDataCallBack<Object>() {
            @Override
            public void onDataSuccessCallBack(Object o) {
                if (dialog!=null){
                    dialog.dismiss();

                }
                MessListResponse bean = (MessListResponse) o;

                if (bean.getRows() == null || bean.getRows().size() == 0) {
                    multipleStatusView.showEmpty();
                } else {
                    PageIndex++;
                    multipleStatusView.showContent();
                     adapt = new MessageListAdapt(getActivity());
                    adapt.addData(bean.getRows());
                    recyMessage.setAdapter(adapt);
                }

            }

            @Override
            public void onDataFailCallBack(Object o) {
                if (dialog!=null){
                    dialog.dismiss();

                }
                if (multipleStatusView!=null){
                    multipleStatusView.showError();
                }
            }
        });


        multipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                multipleStatusView.showLoading();
                initData();
            }
        });

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MsgRefresh(MsgRefreshEvent event){


        initData();
    }

}
